#!/bin/bash
source tools/getenv.sh


if [[ "$env" == "test" || "$env" == "prod" ]]; then
  if [[ ! -h $current_dir ]]; then
    echo -e "$BOLODRED $current_dir 不是软连，rollbackback命令仅支持软连$RESET"
    exit 1
  fi
  # 获取备份文件的个数
  backup_count=$(ls -1d "${real_app_root_path}.backup-"* 2>/dev/null | wc -l)

  # 如果没有备份文件，直接退出
  if [[ $backup_count -eq 0 ]]; then
    echo -e "$BOLODRED 没有备份文件,退出 $RESET"
    exit 0
  fi





#files=$(cd "$CONF_DIR" && find "." -type f -name "*.conf" ! -name "*.bak")
# shellcheck disable=SC2010
files=$(cd "$CONF_DIR" && ls |grep  "conf" |grep -v "\.bak")

# 检查是否有符合条件的文件
if [[ -z "$files" ]]; then
    echo -e "$BOLODRED 没有符合条件的文件！$RESET"
    exit 1
fi

files=$(ls -1dr "${real_app_root_path}.backup-"* 2>/dev/null)
# 打印文件列表和序号
# 输出带有加粗的深白色字体的标题
i=0
while IFS= read -r file; do
  echo  " ----------------------------------------------------------------- "
  echo -e "| $BOLDMAGENTA     $i:  $file $RESET |"
  cd "$file" && git log -2 --graph --all --branches --format=format:'%C(bold blue)%h%C(reset) - %C(green)(%ar)%C(reset) %C(green)(%ai)%C(reset) %C(white)%s%C(reset) %C(white)【%an】 %C(auto)%d%C(reset)'
  echo  " ----------------------------------------------------------------- "
  echo ""
  i=$((i+1))
done <<< "$files"


# 读取用户输入的序号
# shellcheck disable=SC2162
read -p "请输入序号以选择文件创建快捷方式: " input

# 检查输入是否为合法的数字
re='^[0-9]+$'
if ! [[ $input =~ $re ]] || ((input < 0)) || ((input >= i)); then
    echo -e "$BOLODRED 无效的输入序号！$RESET"
    exit 1
fi

# 创建快捷方式
select_backup=$(echo "$files" | sed -n "$((input+1))p")


  # 获取到最近的一个备份文件
  echo "select_backup = $select_backup"
  echo "current_dir = $current_dir"
  # 把当前的软连指向这个

  rollbackStr="cd .. && rm -rf $current_dir && mv ${current_dir}.bak ${current_dir}"
  echo "mv $current_dir ${current_dir}.bak"
  mv "$current_dir" "${current_dir}.bak"
  echo "cd .. && ln -sf $select_backup $app_root_path"
  cd .. && ln -sf "$select_backup" "$app_root_path"
  ls -all "$current_dir"
  echo -e "$BOLODGREEN 回滚成功,后续请手动指向最新目录, , 或者运行 make rollbackback $RESET"

  rollbackAfterRestart

  echo "回滚命令："
  echo -e "$BOLODGREEN $rollbackStr $RESET"
  echo ""
else
  echo -e "$BOLD_WHITE $env 环境，不支持回滚 $RESET"
  exit 0
fi


echo -e "$BOLODGREEN 回滚到指定备份文件成功！ $RESET"

# 软连存在的话，直接替换
# ln -sf dev.8080.conf service.conf